package com.woniu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.dto.UroscopyDto;
import com.woniu.dto.QueryUroscopyDto;
import com.woniu.exception.CheckException;
import com.woniu.model.HisUroscopy;
import com.woniu.mapper.HisUroscopyMapper;
import com.woniu.param.CreateUroscopyParam;
import com.woniu.param.QueryUroscopyParam;
import com.woniu.service.IHisUroscopyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.CopyBeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 尿检表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-11-11
 */
@Service
public class HisUroscopyServiceImpl extends ServiceImpl<HisUroscopyMapper, HisUroscopy> implements IHisUroscopyService {

    @Override
    public QueryUroscopyDto queryUroscopy(QueryUroscopyParam queryUroscopyParam) {
        //时间倒序查找
        QueryWrapper<HisUroscopy> wrapper = new QueryWrapper<HisUroscopy>().orderByDesc("raw_add_time");

        //查询条件
        if (ObjectUtil.isNotNull(queryUroscopyParam.getUroscopyId())) {
            wrapper.eq("uroscopy_id", queryUroscopyParam.getUroscopyId());
        }
        if (ObjectUtil.isNotNull(queryUroscopyParam.getUroscopyName())) {
            wrapper.eq("uroscopy_name", queryUroscopyParam.getUroscopyName());
        }
        if (ObjectUtil.isNotNull(queryUroscopyParam.getCaseId())) {
            wrapper.eq("case_id", queryUroscopyParam.getCaseId());
        }
        if (ObjectUtil.isNotNull(queryUroscopyParam.getCheckId())) {
            wrapper.eq("check_id", queryUroscopyParam.getCheckId());
        }

        List<HisUroscopy> uroscopyList = this.list(wrapper);

        if(ObjectUtil.isNull(uroscopyList)) {
            throw new CheckException(1021, "无尿检结果");
        }

        QueryUroscopyDto dto = new QueryUroscopyDto();
        List<UroscopyDto> uroscopyDtoList = CopyBeanUtil.copyBean(uroscopyList, UroscopyDto.class);
        dto.setUroscopyDtoList(uroscopyDtoList);

        return dto;
    }

    @Override
    public QueryUroscopyDto createUroscopy(CreateUroscopyParam createUroscopyParam) {
        HisUroscopy uroscopy = new HisUroscopy();
        BeanUtils.copyProperties(createUroscopyParam, uroscopy);

        if (!this.save(uroscopy)) {
            throw new CheckException(1021, "尿检结果保存失败");
        }

        QueryUroscopyDto dto = new QueryUroscopyDto();
        BeanUtils.copyProperties(uroscopy, dto);
        return dto;
    }
}
